import { DrawerProps } from '@/components/base/base-drawer/BaseDrawer.vue'
import { getCurrentInstance, ref, defineProps } from 'vue'
import { BaseModel } from '@/entity/base-model'
import { commonAdd, commonGet, commonUpdate } from '@/api/common/common'
import { FormItemProps } from '@/components/base/form-item/props'
import { batchUpdateDisabledFields } from '@/utils/form-item-util'
import { message } from 'ant-design-vue'
export interface FormHook {
  /**
   * 初始化表单数据
   * @param initAfter 初始化之后执行的操作
   */
  init: (initAfter?: Function) => void
  // 取消
  cancel: () => void
  /**
   * 提交表单
   * @param beforeFinish 提交之前的操作
   */
  onFinish: (beforeFinish?: Function) => void
  // 提交失败
  onFinishFailed: (err: any) => void
}
/**
 * 抽屉hooks
 * @param refName 表格refs名称
 * @param api 接口名称
 * @param form 表单数据
 * @param props 属性
 * @param formItem 表单项
 */
export const useForm = (
  api: string,
  form: BaseModel,
  props: { id?: string; type: number },
  formItem: ReturnType<typeof ref<Array<FormItemProps>>>,
): FormHook => {
  const instance = getCurrentInstance()
  const { type, id } = props
  const hooks: FormHook = {
    init: async (initAfter) => {
      if (formItem.value) {
        if (type === 1 || type === 2) {
          const { data } = await commonGet(api, id as string)
          Object.assign(form, data)
          batchUpdateDisabledFields(
            formItem.value,
            formItem.value.map((val) => val.name as unknown as string),
            type === 1,
          )
        } else {
          batchUpdateDisabledFields(
            formItem.value,
            formItem.value.map((val) => val.name as unknown as string),
          )
        }
      }
      // 初始化之后执行的方法
      initAfter?.call(hooks)
    },
    onFinish: async (beforeFinish) => {
      await beforeFinish?.apply(hooks)
      // 新增
      if (type == 0) {
        await commonAdd(api, form)
        instance?.emit('refresh')
      }
      // 修改
      if (type == 2) {
        await commonUpdate(api, form)
        instance?.emit('refresh')
      }
    },
    onFinishFailed: (err: any) => {
      message.error(
        err.errorFields
          .map((val: any) => val.errors)
          .flat(1)
          .join(','),
      )
    },
    cancel: () => {
      instance?.emit('close')
    },
  }
  return hooks
}
